﻿using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace Hopscotch.Presentation.Common.Threading
{
    [DebuggerDisplay("ThreadId = {ThreadId}, ThreadName = {ThreadName}")]
    public class ApplicationDispatcher : IDispatcher
    {
        private readonly Dispatcher dispatcher;
        
        public ApplicationDispatcher(Dispatcher dispatcher)
        {
            this.dispatcher = dispatcher;
        }

        public static IDispatcher CreateFromCurrentThread()
        {
            Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
            if (dispatcher == null || !dispatcher.CheckAccess())
            {
                throw new InvalidOperationException("This must be called from UI thread");
            }

            return new ApplicationDispatcher(dispatcher);
        }

        public int ThreadId
        {
            get { return dispatcher.Thread.ManagedThreadId; }
        }

        public string ThreadName
        {
            get { return dispatcher.Thread.Name; }
        }

        public bool CheckAccess()
        {
            return dispatcher.CheckAccess();
        }

        public void Invoke(Action method)
        {
            dispatcher.Invoke(method);
        }

        public Task RunAsync(Action method)
        {
            var dispatcherOperation = dispatcher.BeginInvoke(method);
            return dispatcherOperation.Task;
        }

    }
}

